﻿using Coldairarrow.Entity.Base_leasesystem_invoicedetail;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Coldairarrow.Entity.Base_leasesystem_merchant;
using Coldairarrow.Entity.Base_leasesystem_service;
using Coldairarrow.Entity.Base_bankcode;
using Coldairarrow.Entity.Base_leasesystem_bankcard;
using Coldairarrow.Entity.Base_leasesystem_billingaddress;
using Coldairarrow.Entity.Base_leasesystem_servicebank;
using Coldairarrow.Entity.Base_leasesystem_serviceaccount;
using Coldairarrow.Entity.Base_leasesystem_transactionbatchsub;
using Coldairarrow.Entity.Base_leasesystem_transactionbatch;
using Coldairarrow.Entity.Base_leasesystem_servicesign;
using Coldairarrow.Entity.Base_leasesystem_invoiceinformation;

namespace Coldairarrow.Business.Base_leasesystem_invoicedetail
{
    public class leasesystem_invoicedetailBusiness : BaseBusiness<leasesystem_invoicedetail>, Ileasesystem_invoicedetailBusiness, ITransientDependency
    {
        public leasesystem_invoicedetailBusiness(IDbAccessor db)
            : base(db)
        {
        }

        #region 外部接口

        public async Task<PageResult<leasesystem_invoicedetail>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<leasesystem_invoicedetail>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<leasesystem_invoicedetail, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<leasesystem_invoicedetail> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(leasesystem_invoicedetail data)
        {
            var merchant = Db.GetEntity<leasesystem_merchant>(data.MID);
            data.MerchantTaxNo = merchant.customTaxIdcd;
            data.SubmitStatus = "1";
            data.ApplicationTime = data.CreateTime;
            var openinvoice = Db.GetIQueryable<leasesystem_invoiceinformation>().Where(a => a.MID == data.MID).FirstOrDefault();
            data.InvoiceRise = openinvoice.InvoiceRise;
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(leasesystem_invoicedetail data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        public async Task<object> GetInvoice_M_S_InID(string id) 
        {
            var Invoice = await GetEntityAsync(id);
            var Merchant = await Db.GetIQueryable<leasesystem_merchant>().Where(a=>a.Id == Invoice.MID).ToListAsync();
            var Service = await Db.GetIQueryable<leasesystem_service>().Where(a => a.Id == Invoice.ServiceProviderId).ToListAsync();
            var MerchantBank = await Db.GetIQueryable<leasesystem_bankcard>().Where(a => a.MID == Invoice.MID).FirstOrDefaultAsync();
            //var M_Address = await Db.GetIQueryable<leasesystem_billingaddress>().Where(a => a.MID == Invoice.MID).FirstOrDefaultAsync();

            var ServiceBank = await Db.GetIQueryable<leasesystem_serviceaccount>().Where(a => a.SID == Invoice.ServiceProviderId).FirstOrDefaultAsync();
            //var S_Address = await Db.GetIQueryable<leasesystem_billingaddress>().Where(a => a.SID == Invoice.ServiceProviderId).FirstOrDefaultAsync();
            var result = new
            {
                Invoice = Invoice,
                Merchant = Merchant,
                Service = Service,
                MerchantBank = MerchantBank,
                ServiceBank = ServiceBank
            };
            return result;
        }

        public async Task<object> GetAddressByMID(string mid) 
        {
            var AddressList = await Db.GetIQueryable<leasesystem_billingaddress>().Where(a => a.MID == mid).ToListAsync();
            var result = new { 
                AddressList = AddressList
            };
            return result;
        }

        public object GetDataListOver(PageInput<ConditionDTO> input)
        {
            var obj = Db.GetIQueryable<leasesystem_transactionbatchsub>()
                .Join(Db.GetIQueryable<leasesystem_transactionbatch>(), a => a.TBID, b => b.Id, (a, b) => new
                {
                    a.Id,
                    a.PaymentOutAmount,
                    a.trxSts,
                    a.CreateTime,
                    b.ServiceProviderName,
                    b.ServiceProviderId,
                    b.MID,
                    
                }).Join(Db.GetIQueryable<leasesystem_merchant>(),a=>a.MID,b=>b.Id,(a,b)=> new{
                    a.Id,
                    a.PaymentOutAmount,
                    a.trxSts,
                    a.CreateTime,
                    a.ServiceProviderName,
                    a.ServiceProviderId,
                    a.MID,
                    b.customerName
                });
            var result = new
            {
                Data = obj.OrderBy($@"{input.SortField} {input.SortType}").Skip((input.PageIndex - 1) * input.PageRows)
                      .Take(input.PageRows),
                Total = obj.Count()
            };
            return result;
        }

        public object GetInvoiceInfoByMID(string batchsubid)
        {
            var batchsub = Db.GetIQueryable<leasesystem_transactionbatchsub>().Where(a=>a.Id == batchsubid)
                .Join(Db.GetIQueryable<leasesystem_transactionbatch>(),a=>a.TBID,b=>b.Id,(a,b)=>new { 
                a,b
                }).FirstOrDefault();

            var Merchantinfo = Db.GetIQueryable<leasesystem_merchant>().Where(a => a.Id == batchsub.b.MID)
                .Join(Db.GetIQueryable<leasesystem_bankcard>(), a => a.Id, b => b.MID, (a, b) => new
                {
                    a.Id,
                    a.customerName,
                    a.customTaxIdcd,
                    a.customCollectorPhone,
                    b.AccountBank,
                    b.BankNo,
                }).Join(Db.GetIQueryable<leasesystem_billingaddress>(),a=>a.Id,b=>b.MID,(a,b)=>new {
                    a.Id,
                    a.customerName,
                    a.customTaxIdcd,
                    a.customCollectorPhone,
                    a.AccountBank,
                    a.BankNo,
                    b.RecipientAddr
                });

            var Servicesigninfo = Db.GetIQueryable<leasesystem_servicesign>().Where(a => a.MID == batchsub.b.MID  && a.ServiceId == batchsub.b.ServiceProviderId).FirstOrDefault();

            var ServiceInfo = Db.GetEntity<leasesystem_service>(batchsub.b.ServiceProviderId);

            var result = new
            {
                merchantinfo = Merchantinfo,
                serviceinfo = ServiceInfo,
                merchantsign = Servicesigninfo
            };
            return result;
        }

        public object GetOpenInvoiceCheck(PageInput<ConditionDTO> input)
        {
            var obj = Db.GetIQueryable<leasesystem_invoicedetail>().Join(Db.GetIQueryable<leasesystem_merchant>(), a => a.MID, b => b.Id, (a, b) => new
            {
                b.Id,
                b.customerName,
                a.CreateTime,
                a.ServiceProviderName,
                a.InvoiceAmount,
                a.InvoiceType,
                a.InvoiceBusinessStatus
            });
            var result = new { 
                Data = obj.Skip((input.PageIndex - 1) * input.PageRows)
                      .Take(input.PageRows),
                Total = obj.Count()
            };
            return result;
        }

        public object GetOpenInvoiceInfo(PageInput<ConditionDTO> input) 
        {
            var newwhere = Db.GetIQueryable<leasesystem_invoicedetail>().Join(
                Db.GetIQueryable<leasesystem_merchant>(), a => a.MID, b => b.Id, (a, b) => new { 
                    a.Id,
                    b.customerName,
                    a.ServiceProviderName,
                    a.InvoiceAmount,
                    a.Amount,
                    a.wlgs,
                    a.wldh,
                    a.InvoiceBusinessStatus
                });

            if (!input.Search.Keyword.IsNullOrEmpty()) {
                newwhere = newwhere.Where(a=>a.customerName.Contains(input.Search.Keyword));
            }
            if (!input.Search.serviceName.IsNullOrEmpty()) {
                newwhere = newwhere.Where(a => a.ServiceProviderName.Contains(input.Search.serviceName));
            }
            if (!input.Search.wlgs.IsNullOrEmpty()) {
                newwhere = newwhere.Where(a => a.wlgs.Contains(input.Search.wlgs));
            }
            if (!input.Search.wldh.IsNullOrEmpty()) {
                newwhere = newwhere.Where(a=>a.wldh == input.Search.wldh);
            }

            var res = new { 
                Data = newwhere.Skip((input.PageIndex - 1) * input.PageRows)
               .Take(input.PageRows),
               Total = Db.GetIQueryable<leasesystem_invoicedetail>().Count()
            };
            return res;
        }
        #endregion

        #region 私有成员

        #endregion
    }
}